package com.ray.business.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.base.service.BaseCustomerService;
import com.ray.base.service.compose.GoodsService;
import com.ray.base.table.entity.BaseCustomer;
import com.ray.base.table.vo.material.model.MaterialModelVO;
import com.ray.business.builder.SaleGoodsBuilder;
import com.ray.business.builder.SaleOutBuilder;
import com.ray.business.builder.SaleOutRecordBuilder;
import com.ray.business.check.SaleCheck;
import com.ray.business.check.SaleOutCheck;
import com.ray.business.enums.SaleOutStatusEnum;
import com.ray.business.enums.SaleStatusEnum;
import com.ray.business.service.ProdSaleOutRecordService;
import com.ray.business.service.ProdSaleOutService;
import com.ray.business.service.ProdSaleRecordService;
import com.ray.business.service.ProdSaleService;
import com.ray.business.table.dto.SaleOutQueryDTO;
import com.ray.business.table.dto.UpdateQuantityDTO;
import com.ray.business.table.entity.ProdSale;
import com.ray.business.table.entity.ProdSaleOut;
import com.ray.business.table.entity.ProdSaleOutRecord;
import com.ray.business.table.entity.ProdSaleRecord;
import com.ray.business.table.params.sale.out.SaleOutCreateParams;
import com.ray.business.table.params.sale.out.SaleOutEditParams;
import com.ray.business.table.params.sale.out.SaleOutQueryParams;
import com.ray.business.table.vo.SaleGoodsVO;
import com.ray.business.table.vo.SaleOutVO;
import com.ray.common.SysMsgCodeConstant;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.system.enums.FileTypeEnum;
import com.ray.system.service.SysFileService;
import com.ray.system.table.entity.SysFile;
import com.ray.util.FileRecordUtil;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.wms.builder.GoodsBuilder;
import com.ray.wms.service.WmsWarehouseService;
import com.ray.wms.service.compose.OutService;
import com.ray.wms.service.compose.StockService;
import com.ray.wms.table.dto.GoodsDTO;
import com.ray.wms.table.dto.OrderCreateDTO;
import com.ray.wms.table.entity.WmsWarehouse;
import com.ray.wms.table.vo.order.GoodsVO;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.config.SysFileConfig;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description:
 * @Class: SaleOutBackApi
 * @Package com.ray.business.api
 * @date 2020/6/8 13:39
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class SaleOutApi {

    @Autowired
    private ProdSaleOutService prodSaleOutService;
    @Autowired
    private ProdSaleOutRecordService prodSaleOutRecordService;
    @Autowired
    private BaseCustomerService baseCustomerService;
    @Autowired
    private WmsWarehouseService wmsWarehouseService;
    @Autowired
    private OutService outService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ProdSaleService prodSaleService;
    @Autowired
    private ProdSaleRecordService prodSaleRecordService;
    @Autowired
    private StockService stockService;
    @Autowired
    private SysFileService sysFileService;
    @Autowired
    private SysFileConfig sysFileConfig;

    /**
     * 查询销售订单列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<SaleOutVO>> pageSaleOuts(CommonPage<SaleOutQueryParams, Page<SaleOutVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, WmsWarehouse> wmsWarehouseMap = new HashMap<>();
        Map<String, BaseCustomer> baseCustomerMap = new HashMap<>();
        CommonPageBuilder<SaleOutQueryDTO, ProdSaleOut> commonPageBuilder = new CommonPageBuilder<>(SaleOutQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<ProdSaleOut> page = prodSaleOutService.page(commonPageBuilder.bulid(), loginUser);
        List<ProdSaleOut> orders = page.getRecords();
        //结果对象
        IPage<SaleOutVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(orders)) {
            pageList.setRecords(orders.stream().map(sysSaleOut -> {
                SaleOutVO orderVO = new SaleOutVO();
                BeanUtil.copyProperties(sysSaleOut, orderVO);
                //查询客信息
                BaseCustomer baseCustomer = baseCustomerMap.get(sysSaleOut.getCustomerCode());
                if (ObjectUtil.isEmpty(baseCustomer)) {
                    baseCustomer = baseCustomerService.queryCustomerByCustomerCode(sysSaleOut.getCustomerCode(), loginUser);
                    baseCustomerMap.put(sysSaleOut.getCustomerCode(), baseCustomer);
                }
                orderVO.setCustomerName(baseCustomer.getCustomerName());
                //查询仓库信息
                WmsWarehouse wmsWarehouse = wmsWarehouseMap.get(sysSaleOut.getWarehouseCode());
                if (ObjectUtil.isEmpty(wmsWarehouse)) {
                    wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(sysSaleOut.getWarehouseCode(), loginUser);
                    wmsWarehouseMap.put(wmsWarehouse.getWarehouseCode(), wmsWarehouse);
                }
                orderVO.setWarehouseName(wmsWarehouse.getWarehouseName());
                return orderVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }


    /**
     * 创建订单
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createOrder(SaleOutCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //查询销售订单数据
        ProdSale prodSale = prodSaleService.querySaleBySaleCode(createParams.getOrderNo(), loginUser);
        new SaleCheck(prodSale).checkNull("销售订单不存在").checkCanIn("销售订单不能出库");
        SaleOutBuilder orderBuilder = new SaleOutBuilder();
        orderBuilder.append(createParams).append(prodSale).appendStatus(SaleStatusEnum.UN_CHECK.getValue()).appendCreate(loginUser);
        //总数
        final List<BigDecimal> quantity = new ArrayList<>();
        //金额统计
        final List<BigDecimal> total = new ArrayList<>();
        //卷数
        final List<Integer> juanTotal = new ArrayList<>();
        List<String> keys = new ArrayList<>();
        //保存商品信息
        List<ProdSaleOutRecord> records = createParams.getGoods().stream().map(saleGoodsParams -> {
            if (keys.contains(saleGoodsParams.getKey())) {
                log.info("物料存在:{}", saleGoodsParams.getKey());
                throw BusinessExceptionFactory.newException("物料重复");
            }
            keys.add(saleGoodsParams.getKey());
            //查询商品是否存在
            ProdSaleRecord prodSaleRecord = prodSaleRecordService.queryRecord(saleGoodsParams, prodSale.getOrderNo(), loginUser);
            if (ObjectUtil.isNull(prodSaleRecord)) {
                log.info("商品{}不在订单中", JSON.toJSONString(saleGoodsParams));
                throw BusinessExceptionFactory.newException("出库商品不在销售订单中");
            }
            //销售退回订单数量
            quantity.add(saleGoodsParams.getQuantity());
            //计算单个商品总价
            total.add(saleGoodsParams.getQuantity().multiply(NumberUtil.null2Zero(prodSaleRecord.getPrice())));
            //保存卷数
            juanTotal.add(saleGoodsParams.getTotal());
            return new SaleOutRecordBuilder().append(saleGoodsParams).appendOrderNo(prodSale.getOrderNo())
                    .appendRecordCode(prodSaleRecord.getCode())
                    .appendPrice(prodSaleRecord.getPrice()).appendCode(orderBuilder.getCode()).appendCreate(loginUser).bulid();
        }).collect(Collectors.toList());
        //保存总数
        orderBuilder.append(quantity.stream().reduce(BigDecimal::add).get());
        //保存总价
        orderBuilder.appendTotal(total.stream().reduce(BigDecimal::add).get());
        //保存卷数
        orderBuilder.appendJuanTotal(juanTotal.stream().mapToInt(Integer::intValue).sum());
        //保存订单信息
        if (!prodSaleOutService.save(orderBuilder.bulid())) {
            log.info("保存订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("保存订单接口异常");
        }
        //更新销售订单完成数量
        UpdateQuantityDTO updateQuantityDTO = new UpdateQuantityDTO();
        updateQuantityDTO.setCode(prodSale.getOrderNo());
        updateQuantityDTO.setUpdateVersion(prodSale.getUpdateVersion());
        updateQuantityDTO.setQuantity(NumberUtil.null2Zero(prodSale.getFinishQuantity()).add(orderBuilder.getQuantity()));
        updateQuantityDTO.setTotal(prodSale.getTotal() + orderBuilder.getTotal());
        updateQuantityDTO.setAmount(NumberUtil.null2Zero(prodSale.getTotalAmount()).add(orderBuilder.getAmount()));
        if (!prodSaleService.updateFinishQuantity(updateQuantityDTO, loginUser)) {
            log.info("更新订单完成数量异常");
            throw BusinessExceptionFactory.newException("更新订单完成数量异常");
        }
        //保存数据
        prodSaleOutRecordService.saveBatch(records);
        //保存文件
        sysFileService.saveFile(orderBuilder.getCode(),FileTypeEnum.SALE_OUT, FileRecordUtil.toFileDTO(createParams.getFiles()),loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }

    /**
     * 编辑订单
     *
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editOrder(SaleOutEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdSaleOut prodSaleOut = prodSaleOutService.querySaleOutByOutCode(editParams.getOutCode(), loginUser);
        new SaleOutCheck(prodSaleOut).checkNull("销售出库单不存在").checkCanEdit("出库单不能编辑");
        ProdSale prodSale = prodSaleService.querySaleBySaleCode(prodSaleOut.getOrderNo(), loginUser);
        new SaleCheck(prodSale).checkNull("销售不存在").checkCanIn("销售订单不能出库");
        SaleOutBuilder orderBuilder = new SaleOutBuilder();
        orderBuilder.append(editParams).appendEdit(loginUser);
        //总数
        final List<BigDecimal> quantity = new ArrayList<>();
        //金额统计
        final List<BigDecimal> total = new ArrayList<>();
        //卷数
        final List<Integer> juanTotal = new ArrayList<>();
        //删除数据
        prodSaleOutRecordService.deleteOrderGoods(editParams.getOutCode(), loginUser);
        //保存商品信息
        List<ProdSaleOutRecord> records = editParams.getGoods().stream().map(purchaseGoodsParams -> {
            //查询商品是否存在
            ProdSaleRecord prodSaleRecord = prodSaleRecordService.queryRecord(purchaseGoodsParams, prodSale.getOrderNo(), loginUser);
            if (ObjectUtil.isNull(prodSaleRecord)) {
                log.info("商品{}不在订单中", JSON.toJSONString(purchaseGoodsParams));
                throw BusinessExceptionFactory.newException(SysMsgCodeConstant.Error.ERR10000022);
            }
            //销售退回订单数量
            quantity.add(purchaseGoodsParams.getQuantity());
            //计算单个商品总价
            total.add(purchaseGoodsParams.getQuantity().multiply(NumberUtil.null2Zero(prodSaleRecord.getPrice())));
            //保存卷数
            juanTotal.add(purchaseGoodsParams.getTotal());
            return new SaleOutRecordBuilder().append(purchaseGoodsParams).appendOrderNo(prodSale.getOrderNo())
                    .appendRecordCode(prodSaleRecord.getCode())
                    .appendPrice(prodSaleRecord.getPrice()).appendCode(orderBuilder.getCode()).appendCreate(loginUser).bulid();
        }).collect(Collectors.toList());
        //保存总数
        orderBuilder.append(quantity.stream().reduce(BigDecimal::add).get());
        //保存总价
        orderBuilder.appendTotal(total.stream().reduce(BigDecimal::add).get());
        //保存卷数
        orderBuilder.appendJuanTotal(juanTotal.stream().mapToInt(Integer::intValue).sum());
        //编辑订单信息
        if (!prodSaleOutService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("编辑订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //更新销售订单完成数量
        UpdateQuantityDTO updateQuantityDTO = new UpdateQuantityDTO();
        updateQuantityDTO.setCode(prodSale.getOrderNo());
        updateQuantityDTO.setUpdateVersion(prodSale.getUpdateVersion());
        updateQuantityDTO.setQuantity(NumberUtil.null2Zero(prodSale.getFinishQuantity()).add(orderBuilder.getQuantity())
                .subtract(prodSaleOut.getQuantity()));
        updateQuantityDTO.setAmount(NumberUtil.null2Zero(prodSale.getTotalAmount()).add(orderBuilder.getAmount())
                .subtract(prodSaleOut.getTotalAmount()));
        updateQuantityDTO.setTotal(prodSale.getTotal() + orderBuilder.getTotal() - prodSaleOut.getTotal());
        if (!prodSaleService.updateFinishQuantity(updateQuantityDTO, loginUser)) {
            log.info("更新订单完成数量异常");
            throw BusinessExceptionFactory.newException("更新订单完成数量异常");
        }
        //保存数据
        prodSaleOutRecordService.saveBatch(records);
        //删除文件
        sysFileService.deleteFile(orderBuilder.getCode(), FileTypeEnum.SALE_OUT.getValue(),loginUser);
        //保存文件
        sysFileService.saveFile(orderBuilder.getCode(),FileTypeEnum.SALE_OUT, FileRecordUtil.toFileDTO(editParams.getFiles()),loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }


    /**
     * 审核通过
     *
     * @param outCode
     * @return
     */
    @Transactional
    public Result<String> passOrder(String outCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdSaleOut prodSaleOut = prodSaleOutService.querySaleOutByOutCode(outCode, loginUser);
        new SaleOutCheck(prodSaleOut).checkNull("销售出库不存在").checkCanCheck("销售出库单已经审核");
        ProdSale prodSale = prodSaleService.querySaleBySaleCode(prodSaleOut.getOrderNo(), loginUser);
        new SaleCheck(prodSale).checkNull("销售单不存在").checkCanIn("销售订单不能出库");
        SaleOutBuilder orderBuilder = new SaleOutBuilder();
        orderBuilder.appendCode(outCode).appendEdit(loginUser).appendStatus(SaleOutStatusEnum.UN_OUT.getValue());
        //编辑订单信息
        if (!prodSaleOutService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("审核订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        OrderCreateDTO orderCreateDTO = new OrderCreateDTO();
        orderCreateDTO.setBusinessCode(outCode);
        orderCreateDTO.setWarehouseCode(prodSaleOut.getWarehouseCode());
        //查询订单商品
        List<ProdSaleOutRecord> records = prodSaleOutRecordService.list(outCode, loginUser);
        List<GoodsDTO> goodsDTOS = records.stream().map(prodSaleOutRecord -> {
            return new GoodsBuilder().append(prodSaleOutRecord).bulid();
        }).collect(Collectors.toList());
        orderCreateDTO.setGoodsDTOS(goodsDTOS);
        //创建订单
        outService.createOrderOut(orderCreateDTO, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, outCode);
    }

    /**
     * 删除
     *
     * @param outCode
     * @return
     */
    @Transactional
    public Result<String> deleteOrder(String outCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdSaleOut prodSaleOut = prodSaleOutService.querySaleOutByOutCode(outCode, loginUser);
        new SaleOutCheck(prodSaleOut).checkNull("销售出库不存在").checkCanCheck("销售出库不能删除");
        ProdSale prodSale = prodSaleService.querySaleBySaleCode(prodSaleOut.getOrderNo(), loginUser);
        new SaleCheck(prodSale).checkNull("销售不存在");
        SaleOutBuilder orderBuilder = new SaleOutBuilder();
        orderBuilder.appendCode(outCode).appendEdit(loginUser).delete();
        //编辑订单信息
        if (!prodSaleOutService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("删除订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("删除订单接口异常");
        }
        //删除数据
        prodSaleOutRecordService.deleteOrderGoods(outCode, loginUser);

        //更新销售订单完成数量
        UpdateQuantityDTO updateQuantityDTO = new UpdateQuantityDTO();
        updateQuantityDTO.setCode(prodSale.getOrderNo());
        updateQuantityDTO.setUpdateVersion(prodSale.getUpdateVersion());
        updateQuantityDTO.setQuantity(NumberUtil.null2Zero(prodSale.getFinishQuantity())
                .subtract(prodSaleOut.getQuantity()));
        updateQuantityDTO.setAmount(NumberUtil.null2Zero(prodSale.getTotalAmount())
                .subtract(prodSaleOut.getTotalAmount()));
        updateQuantityDTO.setTotal(prodSale.getTotal() - prodSaleOut.getTotal());
        if (!prodSaleService.updateFinishQuantity(updateQuantityDTO, loginUser)) {
            log.info("更新订单完成数量异常");
            throw BusinessExceptionFactory.newException("更新订单完成数量异常");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, outCode);
    }


    /**
     * 取消
     *
     * @param outCode
     * @return
     */
    @Transactional
    public Result<String> cancelOrder(String outCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdSaleOut prodSaleOut = prodSaleOutService.querySaleOutByOutCode(outCode, loginUser);
        new SaleOutCheck(prodSaleOut).checkNull("销售出库单不存在").checkCanCancel("销售出库不能取消");
        ProdSale prodSale = prodSaleService.querySaleBySaleCode(prodSaleOut.getOrderNo(), loginUser);
        new SaleCheck(prodSale).checkNull("销售不存在");
        SaleOutBuilder orderBuilder = new SaleOutBuilder();
        orderBuilder.appendCode(outCode).appendStatus(SaleOutStatusEnum.CANCEL.getValue()).appendEdit(loginUser);
        //编辑订单信息
        if (!prodSaleOutService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("取消订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("取消订单接口异常");
        }
        //作废出库订单
        outService.invalidOrderBusinessCode(outCode, loginUser);
        //更新销售订单完成数量
        UpdateQuantityDTO updateQuantityDTO = new UpdateQuantityDTO();
        updateQuantityDTO.setCode(prodSale.getOrderNo());
        updateQuantityDTO.setUpdateVersion(prodSale.getUpdateVersion());
        updateQuantityDTO.setQuantity(NumberUtil.null2Zero(prodSale.getFinishQuantity())
                .subtract(prodSaleOut.getQuantity()));
        updateQuantityDTO.setAmount(NumberUtil.null2Zero(prodSale.getTotalAmount())
                .subtract(prodSaleOut.getTotalAmount()));
        updateQuantityDTO.setTotal(prodSale.getTotal() - prodSaleOut.getTotal());
        if (!prodSaleService.updateFinishQuantity(updateQuantityDTO, loginUser)) {
            log.info("更新订单完成数量异常");
            throw BusinessExceptionFactory.newException("更新订单完成数量异常");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, outCode);
    }


    /**
     * 订单详情
     *
     * @param outCode
     * @return
     */
    public Result<SaleOutVO> viewOrder(String outCode) {
        LoginUser loginUser = LogInUserUtil.get();
        ProdSaleOut prodSaleOut = prodSaleOutService.querySaleOutByOutCode(outCode, loginUser);
        new SaleOutCheck(prodSaleOut).checkNull("销售退货单不存在");
        SaleOutVO saleVO = new SaleOutVO();
        BeanUtil.copyProperties(prodSaleOut, saleVO);
        //查询客信息
        BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(prodSaleOut.getCustomerCode(), loginUser);
        if (ObjectUtil.isNotNull(baseCustomer)) {
            saleVO.setCustomerName(baseCustomer.getCustomerName());
        }
        //查询仓库信息
        WmsWarehouse wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(prodSaleOut.getWarehouseCode(), loginUser);
        if (ObjectUtil.isNotNull(wmsWarehouse)) {
            saleVO.setWarehouseName(wmsWarehouse.getWarehouseName());
        }
        //查询
        List<ProdSaleOutRecord> prodSaleOutRecords = prodSaleOutRecordService.list(outCode, loginUser);
        Map<String, MaterialModelVO> modelMap = new HashMap<>();
        List<SaleGoodsVO> purchaseGoodsVOS = prodSaleOutRecords.stream().map(prodSaleOutRecord -> {
            MaterialModelVO materialModelVO = modelMap.get(prodSaleOutRecord.getGoodsCode());
            if (ObjectUtil.isNull(materialModelVO)) {
                materialModelVO = goodsService.queryGoodsByCode(prodSaleOutRecord.getGoodsCode(), loginUser);
                modelMap.put(prodSaleOutRecord.getGoodsCode(), materialModelVO);
            }
            return new SaleGoodsBuilder().append(prodSaleOutRecord).append(materialModelVO).bulid();
        }).collect(Collectors.toList());
        saleVO.setGoods(purchaseGoodsVOS);
        //查询图片信息
        List<SysFile> files = sysFileService.queryFiles(outCode, FileTypeEnum.SALE_OUT.getValue(),loginUser);
        saleVO.setFiles(FileRecordUtil.toFileVO(files,sysFileConfig));
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, saleVO);
    }

    public Result<List<SaleGoodsVO>> listGoods(@Valid SaleOutQueryParams queryParams) {
        Assert.hasLength(queryParams.getOrderNo(),"参数订单不能为空");
        LoginUser loginUser = LogInUserUtil.get();
        //查询生效的出库单
        List<ProdSaleOut> prodSaleOuts = prodSaleOutService.listFinishByOrderNos(Arrays.asList(queryParams.getOrderNo()), loginUser);
        List<String> outCodes = prodSaleOuts.parallelStream().map(ProdSaleOut::getOutCode).collect(Collectors.toList());
        List<ProdSaleOutRecord> prodSaleOutRecords = prodSaleOutRecordService.listByOrderNo(queryParams.getOrderNo(), outCodes, loginUser);
        Map<String, MaterialModelVO> modelMap = new HashMap<>();
        List<SaleGoodsVO> goodsVOList = prodSaleOutRecords.stream().map(prodSaleOutRecord -> {
            MaterialModelVO materialModelVO = modelMap.get(prodSaleOutRecord.getGoodsCode());
            if (ObjectUtil.isNull(materialModelVO)) {
                materialModelVO = goodsService.queryGoodsByCode(prodSaleOutRecord.getGoodsCode(), loginUser);
                modelMap.put(prodSaleOutRecord.getGoodsCode(), materialModelVO);
            }
            return new SaleGoodsBuilder().append(prodSaleOutRecord).append(materialModelVO).bulid();
        }).collect(Collectors.toList());
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, goodsVOList);
    }

    /**
     * 查询出库单商品列表
     *
     * @param queryParams
     * @return
     */
    public Result<List<GoodsVO>> listOutGoods(SaleOutQueryParams queryParams) {
        Assert.notNull(queryParams, "参数不能为空");
        Assert.hasLength(queryParams.getOrderNo(), "订单号不能为空");

        LoginUser loginUser = LogInUserUtil.get();
        ProdSale prodSale = prodSaleService.querySaleBySaleCode(queryParams.getOrderNo(), loginUser);
        new SaleCheck(prodSale).checkNull("销售订单不存在");
        List<GoodsVO> goodsVOS = new ArrayList<>();
        //循环
        prodSaleRecordService.list(queryParams.getOrderNo(), loginUser).forEach(prodSaleRecord -> {
            GoodsDTO goodsDTO = new GoodsDTO();
            goodsDTO.setWarehouseCode(prodSale.getWarehouseCode());
            goodsDTO.setUnit(prodSaleRecord.getUnit());
            goodsDTO.setGoodsCode(prodSaleRecord.getGoodsCode());
            goodsDTO.setOrderNo("0");
            goodsVOS.addAll( stockService.queryStockDetails(goodsDTO,prodSaleRecord.getPrice()));
        });
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, goodsVOS);
    }
}
